package com.scalar.chiptrack.adaptor.umc;

import java.util.ArrayList;
import java.util.HashMap;

import java.io.File;

import com.scalar.ScalarException;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.FabSortLot;
import com.scalar.chiptrack.adaptor.ShippedLot;
import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.XLSParserImpl;
import com.scalar.chiptrack.adaptor.utils.CSVParserImpl;
import com.scalar.chiptrack.adaptor.dao.FabSortAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.jobs.JobHandler;

public final class UMCDataParser extends JobHandler implements AdaptorConstants
{
    private HashMap<String, FabSortLot> m_wipDataMap        = new HashMap<String, FabSortLot>();
    private HashMap<String, ShippedLot> m_shipDataMap       = new HashMap<String, ShippedLot>();
    private HashMap<String, FabSortLot> m_sortWipDataMap    = new HashMap<String, FabSortLot>();
    private HashMap<String, ShippedLot> m_sortShipDataMap   = new HashMap<String, ShippedLot>();
    private HashMap<String, FabSortLot> m_sortBinDataMap    = new HashMap<String, FabSortLot>();

    private Logger m_parserLogger       = null;
    private String m_dataOutputDir      = null;

    public UMCDataParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = AdaptorUtils.getDataOutputDir( VENDOR_NAME_UMC , WIP_TYPE_FAB );
            if ( m_dataOutputDir != null )
            {
                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );

                m_parserLogger = AdaptorUtils.getDataParserLogger( m_dataOutputDir, VENDOR_NAME_UMC );
                // Both Parser and DAO should be logging into same file
                FabSortAdaptorDAO.setLogger( m_parserLogger );
                ShippedLotDAO.setLogger( m_parserLogger );
                AdaptorUtils.setLogger( m_parserLogger );
            }
        }
        catch( ScalarException se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading UMC Adaptor output directory details from database, Exception: " + se );
            se.printStackTrace();
            throw se;
        }
    }

    public static void main( String args[] ) throws Exception
    {
        new UMCDataParser().execute();
    }

    public void execute() throws Exception
    {
        AdaptorUtils.printHeader(VENDOR_NAME_UMC , CONSTANT_PARSER );

        File doneDestDir = new File( m_dataOutputDir + "/done" );
        File dataoutDir  = new File( m_dataOutputDir );

        File[] fileList = dataoutDir.listFiles();

        if ( ( fileList == null ) || (fileList.length <= 3))
        {
            log("No file found in directory: " + dataoutDir);
            System.out.println("No file found in directory: " + dataoutDir );
            throw new ScalarException("No file found in directory: " + dataoutDir+ "----\n\n" );
        }

        ArrayList<File> successFileList       = new ArrayList<File>();
        boolean success                 = false;

        for( int i = 0; i < fileList.length; i++ )
        {

            if( fileList[i].isDirectory() )
            {
                continue;
            }
            if( fileList[i].getName() != null && fileList[i].getName().startsWith( UMCAdaptor.FILE_NAME_STANDARD_WIP_SUMMARY ) )
            {
                try
                {
                    parseDynamicWipReport (fileList[i].getAbsolutePath() ) ;
                    // Move the file to 'done' List
                    successFileList.add( fileList[i] );
                    success = true;
                }
                catch( Exception e )
                {
                    success = false;
                    log( "Exception while parsing and storing file: " + fileList[i].getAbsolutePath() + "\nException: " + e );
                    e.printStackTrace();
                    throw e;
                }
            }

            if( fileList[i].getName() != null && fileList[i].getName().startsWith( UMCAdaptor.FILE_NAME_SHIPPING_INFO ) )
            {
                try
                {
                    parseDynamicShipReport(fileList[i].getAbsolutePath());
                    // Move the file to 'done' List
                    successFileList.add( fileList[i] );
                    success = true;
                }
                catch( Exception e )
                {
                    success = false;
                    log( "Exception while parsing and storing file: " + fileList[i].getAbsolutePath() + "\nException: " + e );
                    e.printStackTrace();
                    throw e;
                }
            }
            if( fileList[i].getName() != null && fileList[i].getName().startsWith( UMCAdaptor.FILE_NAME_SORT_LOT_BIN_SUMMARY ) )
            {
                try
                {
                    parseSortBinInfo( fileList[i].getAbsolutePath()  );

                    // Move the file to 'done' List
                    successFileList.add( fileList[i] );
                    success = true;
                }
                catch( Exception e )
                {
                    success = false;
                    log( "Exception while parsing and storing file: " + fileList[i].getAbsolutePath() + "\nException: " + e );
                    e.printStackTrace();
                    throw e;
                }
            }
        }
        // Fab Lot Information Save
        try
        {
            if( m_wipDataMap.isEmpty() == false )
            {
                FabSortAdaptorDAO.saveFabLot( null, m_wipDataMap.values().iterator(), WIP_TYPE_FAB, VENDOR_NAME_UMC );
            }
            else
            {
               System.out.println( "This is UMC Data Parser FAB Part Number List is empty" ); 
               FabSortAdaptorDAO.closeFabSortLot( null, WIP_TYPE_FAB, VENDOR_NAME_UMC );
            }
        }
        catch( Exception e )
        {
            success = false;
            log( "Exception while storing UMC wip Data: " + e );
            e.printStackTrace();
            throw e;
        }
        // Save Shipped Lot Information
        try
        {
            if( m_shipDataMap.isEmpty() == false )
            {
                ShippedLotDAO.saveShippedLot( null, m_shipDataMap.values().iterator()  );
            }
            success = true;
        }
        catch( Exception e)
        {
            success = false;
            log( "Exception while storing UMC FAB Shipping Data: " + e );
            e.printStackTrace();
            throw e;
        }
        try
        {
            if ( m_sortBinDataMap.isEmpty() == false )
            {
                FabSortAdaptorDAO.saveSortBinData( null, m_sortBinDataMap.values().iterator() );
            }
            success = true;
            m_sortBinDataMap.clear();
        }
        catch(Exception e)
        {
            success = false;
            System.out.println(" Exception Occrred While Saving the Sort Binning Info " +e );
            throw e;
        }
        try
        {
            if ( m_sortWipDataMap.isEmpty() == false )
            {
                log( "Updating SORT Lot Information" );
                FabSortAdaptorDAO.saveSortLot( null, m_sortWipDataMap.values().iterator(), WIP_TYPE_SORT, VENDOR_NAME_UMC );
            }
            else
            {
                System.out.println( "This is UMC Data Parser SORT Part Number List is empty" );
                FabSortAdaptorDAO.closeFabSortLot( null, WIP_TYPE_SORT, VENDOR_NAME_UMC );
            }
        }
        catch ( Exception e )
        {
            success = false;
            log( "ERROR!! ERROR!! ERROR!! Could not update SORT Data information into database: " + e );
            e.printStackTrace();
            throw e;
        }

        try
        {
            // Save shipping info -
            if ( m_sortShipDataMap.isEmpty() == false )
            {
                log( "Updating SORT shipment Information" );
                ShippedLotDAO.saveShippedLot( null, m_sortShipDataMap.values().iterator() );
            }
        }
        catch ( Exception e )
        {
            success = false;
            log( "ERROR!! ERROR!! ERROR!! Could not update UMC Sort Shipping information into database: " + e );
            e.printStackTrace();
            throw e;
        }
        // To Close the Drop Out Lots
        AdaptorDAO.closeDropOutLots( VENDOR_NAME_UMC );
        // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
        AdaptorDAO.sendAllNotifications( VENDOR_NAME_UMC, true, true, true );

        int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( UMCAdaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);

        // Update Adaptor_Run_Info table
        try
        {
            if ( success == true )
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, UMCAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
            }
        }
        catch ( ScalarException se )
        {
            success = false; //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, UMCAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log( "WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se );
            throw se;
        }

       // Step 7
       // Move the successful files to 'done' directory
       if ( success )
       {
           AdaptorUtils.moveFilesToDone( successFileList, doneDestDir );
       }
    }

    private void parseDynamicWipReport( String fileName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );
        ParserResult result     = null;
        FabSortLot fabSortLot   = null;
        String lotNumber        = null;
        String partNumber       = null;
        
        try
        {
            File detailWipFile = new File( fileName );
            if ( detailWipFile.exists() == false )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "\nParsing the file for Dynamic WIP Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for Dynamic WIP Report..." );

            Parser parser = ParserFactory.getCSVParser( detailWipFile, ',' );

            ((CSVParserImpl)parser).setHeaderRowIdx(1);
            ((CSVParserImpl)parser).setDataStartRowIdx(2);

            result = parser.parse();

            //System.out.println("result.getString() = " + result.getHeadings() );

            while ( result.next() )
            {
                partNumber = result.getString("SHP_PRD_NO");
                lotNumber = result.getString("LOT");

                if( lotNumber != null && lotNumber.trim().length() > 2 && partNumber != null && partNumber.trim().length() > 2 )
                {
                    if ( result.getString("STAGE") != null && ( "CP".equalsIgnoreCase( result.getString("STAGE") ) || "SORT".equalsIgnoreCase( result.getString("STAGE") ) ) )
                    {
                        fabSortLot = m_sortWipDataMap.get( partNumber + lotNumber );
                        if ( fabSortLot == null )
                        {
                            fabSortLot = new FabSortLot(VENDOR_NAME_UMC, WIP_TYPE_SORT );
                            m_sortWipDataMap.put( partNumber + lotNumber , fabSortLot );
                        }
                    }
                    else
                    {
                        fabSortLot = m_wipDataMap.get( partNumber + lotNumber );
                        if (fabSortLot == null)
                        {
                            fabSortLot = new FabSortLot( VENDOR_NAME_UMC, WIP_TYPE_FAB );
                            m_wipDataMap.put( partNumber + lotNumber, fabSortLot);
                        }
                    }
                    int quantity = 0;
                    if (fabSortLot.getQtyIn() != null)
                    {
                        try
                        {
                            quantity = Integer.parseInt(fabSortLot.getQtyIn());
                        }
                        catch (NumberFormatException ignore)
                        {
                        }
                        quantity += result.getInt("WIP_QTY");
                    }
                    else
                    {
                        quantity = result.getInt("WIP_QTY");
                    }

                    String dateIn           = null;
                    String shipFcstDate     = null;
                    String shipConfDate     = null;

                    if( result.getString("WS_DATE") != null && result.getString("WS_DATE").trim().length() > 8 )
                    {
                        dateIn = StringUtils.formatDate( result.getString("WS_DATE"), "yyyy/MM/dd HH:mm:ss", "MM/dd/yyyy HH:mm:ss");
                    }

                    if( result.getString("SHIP_CONF_DATE") != null && result.getString("SHIP_CONF_DATE").trim().length() > 8 )
                    {
                        shipConfDate = StringUtils.formatDate( result.getString("SHIP_CONF_DATE"), "yyyy/MM/dd", "MM/dd/yyyy");
                    }

                    if( result.getString("SHIP_FCST_DATE") != null && result.getString("SHIP_FCST_DATE").trim().length() > 8 )
                    {
                        shipFcstDate = StringUtils.formatDate( result.getString("SHIP_FCST_DATE"), "yyyy/MM/dd", "MM/dd/yyyy");
                    }

                    if( quantity > 0 && quantity <= 25)
                    {
                        fabSortLot.setFabId ( result.getString("FAB_ID") );
                        fabSortLot.setFabPartName ( null );
                        fabSortLot.setProcessGen ( result.getString("PROCESSGEN") );
                        fabSortLot.setProcess ( result.getString("PROCESS") );
                        fabSortLot.setWsQty ( result.getString("WS_QTY") );
                        fabSortLot.setSoNumber ( null );
                        fabSortLot.setPriorty ( result.getString("PRIORITY") );
                        fabSortLot.setLayerPosition ( result.getString("LAYER_POSITION") );
                        fabSortLot.setLayer( result.getString("LAYER") );
                        fabSortLot.setShip_fcst_date( shipFcstDate );
                        fabSortLot.setShip_conf_date( shipConfDate );

                        fabSortLot.setLotId( lotNumber);
                        fabSortLot.setFabLotNumber( lotNumber );
                        fabSortLot.setCustProduct( partNumber );
                        fabSortLot.setDateIn( dateIn );
                        fabSortLot.setQtyIn( quantity + "" );
                        fabSortLot.setStage( result.getString("ROUTEDESC") );
                        fabSortLot.setStagePosition( result.getString("ROUTESEQUENCE") );
                        if ("HOLD".equalsIgnoreCase(result.getString("LOTSTATUS") ) )
                        {
                            fabSortLot.setLotStatus( LOT_STATUS_HOLD );
                        }
                        else
                        {
                            fabSortLot.setLotStatus( LOT_STATUS_RUNNING );
                        }

                        fabSortLot.setPoNumber( result.getString("PO"));
                        fabSortLot.setGrossDie( result.getString("GROSS_DIE") );
                        fabSortLot.setWaferID( result.getString("WAFER_NO(For 12 inch only)") );
                        fabSortLot.setVendorLot( lotNumber );
                        fabSortLot.setForcastedDateOut( shipConfDate );
                        fabSortLot.setOutLookDate ( shipFcstDate );
                        if ( result.getString("LOTTYPE") == null || "M".equalsIgnoreCase(result.getString("LOTTYPE") ) || "P".equalsIgnoreCase(result.getString("LOTTYPE") ))
                        {
                             fabSortLot.setLotCategory ( LOT_CATEGORY_TYPE_PROD );
                        }
                        else if ("R".equalsIgnoreCase(result.getString("LOTTYPE") ) )
                        {
                            fabSortLot.setLotCategory ( LOT_CATEGORY_TYPE_RMA );
                        }
                        else
                        {
                            fabSortLot.setLotCategory ( LOT_CATEGORY_TYPE_ENGG );
                        }
                    }
                }
            }
        }
        catch( Exception e )
        {
            log( "Exception while parsing Dynamic UMC Wip Summary Data: " + e );

            throw new ScalarException( "Exception while parsing Dynamic UMC Wip Summary Data: ", e );
        }
    }

    private void parseDynamicShipReport( String fileName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );
        ParserResult result     = null;
        ShippedLot shippedLot   = null;
        String lotNumber        = null;
        String partNumber       = null;
        String shipDate         = null;
        
        try
        {
            File detailWipFile = new File( fileName );
            if ( detailWipFile.exists() == false )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "\nParsing the file for Dynamic SHIP Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for Dynamic SHIP Report..." );

            Parser parser = ParserFactory.getCSVParser( detailWipFile, ',' );

            ((CSVParserImpl)parser).setHeaderRowIdx(0);
            ((CSVParserImpl)parser).setDataStartRowIdx(1);

            result = parser.parse();

            //System.out.println("result.getString() = " + result.getHeadings() );
            int headerRow = -1;

            while ( result.next() )
            {
                if ( "SHP_PRD_NO".equalsIgnoreCase( result.getString(0) ) )
                {
                    headerRow =  result.getFileRowIdx();
                    break;
                }
            }

             parser = ParserFactory.getCSVParser( detailWipFile, ',' );

            ((CSVParserImpl)parser).setHeaderRowIdx(headerRow);
            ((CSVParserImpl)parser).setDataStartRowIdx(headerRow+1);

             result = parser.parse();
             //System.out.println("result.getHeadings() = " + result.getHeadings());
             while (result.next() )
             {
                partNumber = result.getString("SHP_PRD_NO");
                lotNumber = result.getString("LOT_NO");
                if ( result.getString("INV_DATE") != null )
                {
                    shipDate   = StringUtils.formatDate(result.getString("INV_DATE"), "yyyy/MM/dd", "MM/dd/yyyy" );
                }
               String shipTo = null;
               if ( result.getString("SHPTO_CODE") != null )
               {
                    shipTo = result.getString("SHPTO_CODE").split("-")[1];
               }

               if( lotNumber != null && lotNumber.trim().length() > 2 && partNumber != null && partNumber.trim().length() > 2
                        && !partNumber.startsWith( "Customer Product" ) )
               {
                   if ( result.getInt("SHIP_D_QTY")  > 0 )
                   {
                        shippedLot = ( ShippedLot ) m_sortShipDataMap.get( lotNumber + partNumber + shipTo + shipDate );

                        if ( shippedLot == null )
                        {
                            shippedLot = new ShippedLot(VENDOR_NAME_UMC, LOCATION_TYPE_SORT );
                            m_sortShipDataMap.put( lotNumber + partNumber + shipTo + shipDate, shippedLot );
                        }
                   }
                   else
                   {
                        shippedLot = ( ShippedLot ) m_shipDataMap.get( partNumber + lotNumber+ shipTo + shipDate + result.getString("Customer PO") );
                        if ( shippedLot == null )
                        {
                            shippedLot = new ShippedLot( VENDOR_NAME_UMC, WIP_TYPE_FAB );
                            m_shipDataMap.put( partNumber + lotNumber+ shipTo + shipDate + result.getString("Customer PO") , shippedLot );
                        }
                   }
                   int wquantity = 0;
                   int dquantity = 0;
                   String waferIds = null;

                   if ( shippedLot.getShipQty() != null )
                   {
                        try
                        {
                           wquantity = Integer.parseInt( shippedLot.getShipQty() );
                           dquantity = Integer.parseInt( shippedLot.getShipDieQty() );
                        }
                        catch ( NumberFormatException ignore )
                        {
                           wquantity = 0;
                           dquantity= 0;
                        }
                        wquantity += result.getInt("SHIP_W_QTY");
                        dquantity += result.getInt("SHIP_D_QTY");
                   }
                   else
                   {
                        wquantity = result.getInt("SHIP_W_QTY");
                        dquantity = result.getInt("SHIP_D_QTY");

                   }
                   if ( shippedLot.getWaferID() != null )
                   {
                        waferIds =  shippedLot.getWaferID() + ";"+result.getString("WAFER_NO");
                   }
                   else
                   {
                       waferIds = result.getString("WAFER_NO");
                   }

                   if ( wquantity > 0)
                   {

                       shippedLot.setPartNumber( partNumber);
                       shippedLot.setLotNumber( lotNumber );
                       shippedLot.setFabLotNumber( lotNumber );
                       shippedLot.setShipDate( shipDate );
                       shippedLot.setShipQty( wquantity +"" );
                       shippedLot.setInvoiceNumber( result.getString("INV_NO") );
                       shippedLot.setCustomerPO( result.getString("Customer PO") );
                       shippedLot.setCustomerSO(result.getString("SO_NO") );
                       shippedLot.setNextLocation( shipTo );
                       shippedLot.setShipDieQty( dquantity +"");
                       if ((result.getString("ETD") != null) && (result.getString("ETD").trim().length() > 2) )
                       {
                           shippedLot.setEtd( StringUtils.formatDate(result.getString("ETD"), "yyyy/MM/dd HH:mm:ss", "MM/dd/yyyy HH:mm:ss") );
                       }
                       if ((result.getString("ETA") != null) && (result.getString("ETA").trim().length() > 2) )
                       {
                           shippedLot.setEta( StringUtils.formatDate(result.getString("ETA"), "yyyy/MM/dd HH:mm:ss", "MM/dd/yyyy HH:mm:ss") );
                       }

                       if ( result.getString("FLT_INFO_1") != null )
                       {
                           shippedLot.setFlightNumber( result.getString("FLT_INFO_1").split("  ")[0] );
                       }
                       if ( result.getString("MAWB_NO") != null )
                       {
                           shippedLot.setHawb( result.getString("MAWB_NO").replaceAll("-","") );
                       }
                       if ( result.getString("HAWB_NO") != null )
                       {
                           shippedLot.setMawb( result.getString("HAWB_NO").replaceAll("-","") );
                       }
                       shippedLot.setShippingDoc( result.getString("SHIP_NO") );
                       shippedLot.setWaferID( waferIds );
                  }
               }
            }
        }
        catch( Exception e )
        {
            log( "Exception while parsing Dynamic UMC Ship Summary Data: " + e );

            throw new ScalarException( "Exception while parsing Dynamic UMC Ship Summary Data: ", e );
        }
    }
    
    private void parseSortBinInfo(  String fileName) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );
        ParserResult result     = null;
        String partNumber       = null;
        String lotNumber        = null;
        String testPgm          = null;
        String tester           = null;
        String totalYield       = null;
        String dateIn           = null;
        int gdpw        = 0;
        int waferQty    = 0;
        int totalgoodDie     = 0;
        int waferId     = 0;
        FabSortLot sortBinLot = null;
        try
        {
            File shipFile = new File( fileName );
            if ( shipFile.exists() == false )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "Parsing the file for Binning Info..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "Parsing the file for Binning Info..." );

            int headerRow = -1;

            Parser parser = ParserFactory.getXLSParser( shipFile );

            ((XLSParserImpl)parser).setHeaderRowIdx( -1 );
            ((XLSParserImpl)parser).setDataStartRowIdx(0);

            result = parser.parse();
            while ( result.next() )
            {
                if ( "Customer Product:".equalsIgnoreCase( result.getString(0) ) )
                {
                    partNumber =  result.getString(2);
                }
                if ( "UMC Lot:".equalsIgnoreCase( result.getString(0) ) )
                {
                    lotNumber =  result.getString(2);
                    if ( lotNumber != null && lotNumber.trim().length() >0 )
                    {
                        if ( lotNumber.indexOf("(") != -1 )
                        {
                            lotNumber = lotNumber.substring( 0 , lotNumber.indexOf("("));
                        }
                    }
                }
                if ( "Program:".equalsIgnoreCase( result.getString(0) ) )
                {
                    testPgm =  result.getString(2);
                }
                if ( "Tester:".equalsIgnoreCase( result.getString(0) ) )
                {
                    tester =  result.getString(2);
                }
                if ( "Gross Dice:".equalsIgnoreCase( result.getString(0) ) )
                {
                    gdpw =  result.getInt(2);
                }
                if ( "Ship Slice:".equalsIgnoreCase( result.getString(0) ) )
                {
                    waferQty =  result.getInt(2);
                }
                if ( "Ship Dice:".equalsIgnoreCase( result.getString(0) ) )
                {
                    totalgoodDie =  result.getInt(2);
                }
                if ( "Ship Yield:".equalsIgnoreCase( result.getString(0) ) )
                {
                    if ( result.getString(2) != null )
                    {
                        totalYield = result.getString(2).replaceAll("%","");
                    }
                }

                if ( "Ship Time:".equalsIgnoreCase( result.getString(0) ) )
                {
                    if ( result.getString(2) != null )
                    {
                        dateIn = StringUtils.formatDate( result.getString(2), "yyyy/MM/dd", "MM/dd/yyyy");
                    }
                }

                if ( "Wafer Id".equalsIgnoreCase( result.getString(0) ) )
                {
                    headerRow =  result.getFileRowIdx();
                    break;
                }
            }

            ((XLSParserImpl)parser).setHeaderRowIdx(headerRow);
            ((XLSParserImpl)parser).setDataStartRowIdx(headerRow+1);

             result = parser.parse();
             while (result.next() )
             {
                 if ("Total".equalsIgnoreCase(result.getString(0)) )
                 {
                     break;
                 }
                 waferId = result.getInt(0);

                 if ( partNumber != null && partNumber.trim().length()>0 && lotNumber != null && lotNumber.trim().length() > 0 && waferId > 0 && waferId < 26 )
                 {
                     //SortLotBinData cpYieldStatus = new SortLotBinData();

                    sortBinLot = ( FabSortLot ) m_sortBinDataMap.get( partNumber + lotNumber + waferId);

                    if ( sortBinLot == null )
                    {
                        sortBinLot = new FabSortLot( VENDOR_NAME_UMC, LOCATION_TYPE_SORT );
                        m_sortBinDataMap.put( partNumber + lotNumber + waferId  , sortBinLot );
                    }
                    sortBinLot.setCustProduct( partNumber );
                    sortBinLot.setLotId( lotNumber );
                    sortBinLot.setFabLotNumber( lotNumber );
                    sortBinLot.setWaferID( waferId+"" );
                    sortBinLot.setQtyIn( waferQty +"");
                    sortBinLot.setTotalgoodDieQtyIn( (gdpw*waferQty) );
                    sortBinLot.setTotalprobeQtyIn( totalgoodDie);
                    sortBinLot.setDateOut( dateIn );
                    sortBinLot.setDateIn( dateIn );
                    sortBinLot.setTesterNo( tester );
                    sortBinLot.setTestProgram( testPgm );
                    sortBinLot.setGoodDieQtyIn(result.getInt("Good Die"));
                    sortBinLot.setRejectedQtyIn(gdpw-result.getInt("Good Die") );
                    sortBinLot.setShipYield((result.getDouble("Yield")*100)+"".replaceAll("%","") );
                    sortBinLot.setTotalYield( Float.parseFloat(totalYield) ); // if sets as 0, in the PROC Yield Calculating (INQTY *100.00/OUTQTY)
                    sortBinLot.setBinNumber( "Bin1" );

                    /*cpYieldStatus.setProduct( partNumber );
                    cpYieldStatus.setLotNumber(lotNumber );
                    cpYieldStatus.setFablotNumber( lotNumber );
                    cpYieldStatus.setTemp(result.getString("Temperature"));
                    cpYieldStatus.setProbeId(result.getString("Prober ID"));
                    cpYieldStatus.setProbeCard(result.getString("Probe Card"));
                    cpYieldStatus.setInsertion(result.getString("Insertion"));
                    cpYieldStatus.setGrossDice( result.getInt("GDPW")+"");
                    cpYieldStatus.setGoodDice( result.getInt("good Dies")+"");
                    cpYieldStatus.setShipYield( result.getString("Yield").replaceAll("%","") );
                    cpYieldStatus.setWaferId( waferId+"");
                    cpYieldStatus.setDateIn( result.getString("Test In Date") );
                    int[] binQty = new int[100];
                    int binNo = 0;
                    for(int i=1; i<=100; i++ )
                    {
                        binQty[binNo++] = result.getInt("BIN"+i);
                    }
                    cpYieldStatus.setBinQty( binQty );

                    cpYieldList.add( cpYieldStatus );*/
                     
                 }

             }
        }
        catch ( Exception ex )
        {
            ex.printStackTrace();
            throw ex;
        }
    } // end of prase parseShipReport method

    private void log( String message )
    {

        if( message == null ) return;

        if( m_parserLogger != null )
        {
            synchronized( m_parserLogger )
            {
                m_parserLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}
